package dialog

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type Response struct {
	Data  interface{}
	Error string
}

type Request struct {
	Channel string
	Type    string
	Payload interface{}
}

const EventName = "dialog"

func EventsHandler(ctx context.Context, optionalData ...interface{}) {
	request := new(Request)
	err := json.Unmarshal([]byte(optionalData[0].(string)), request)
	if err != nil {
		return
	}
	runtime.LogDebugf(ctx, "%+v", request)

	module := request.Type
	response := &Response{}
	switch module {
	case TypeFile:
		defer func() {
			runtime.EventsEmit(ctx, request.Channel, response)
		}()
		options := runtime.OpenDialogOptions{}
		jsonBytes, _ := json.Marshal(request.Payload)
		err := json.Unmarshal(jsonBytes, &options)
		data, err := OpenFileDialog(ctx, options)
		response.Data = data
		response.Error = errorString(err)
	case TypeFiles:
		defer func() {
			runtime.EventsEmit(ctx, request.Channel, response)
		}()
		options := runtime.OpenDialogOptions{}
		jsonBytes, _ := json.Marshal(request.Payload)
		err := json.Unmarshal(jsonBytes, &options)
		data, err := OpenMultipleFilesDialog(ctx, options)
		response.Data = data
		response.Error = errorString(err)
	case TypeDir:
		defer func() {
			runtime.EventsEmit(ctx, request.Channel, response)
		}()
		options := runtime.OpenDialogOptions{}
		jsonBytes, _ := json.Marshal(request.Payload)
		err := json.Unmarshal(jsonBytes, &options)
		data, err := OpenDirectoryDialog(ctx, options)
		response.Data = data
		response.Error = errorString(err)
	case TypeSave:
		defer func() {
			runtime.EventsEmit(ctx, request.Channel, response)
		}()
		options := runtime.SaveDialogOptions{}
		jsonBytes, _ := json.Marshal(request.Payload)
		err := json.Unmarshal(jsonBytes, &options)
		data, err := SaveFileDialog(ctx, options)
		response.Data = data
		response.Error = errorString(err)
	case TypeMessage:
		defer func() {
			runtime.EventsEmit(ctx, request.Channel, response)
		}()
		defer func() {
			err := recover()
			if err != nil {
				response.Error = errorString(err.(error))
			}
		}()
		options := runtime.MessageDialogOptions{}
		jsonBytes, _ := json.Marshal(request.Payload)
		runtime.LogDebug(ctx, string(jsonBytes))
		err := json.Unmarshal(jsonBytes, &options)
		runtime.LogDebugf(ctx, "%+v", options)
		//data, err := MessageDialog(ctx, options)
		//response.Data = data
		if err != nil {
			response.Error = errorString(err)
		} else {
			response.Error = errorString(errors.New("暂不支持"))
		}
	}
}

func errorString(err error) string {
	if err != nil {
		return err.Error()
	} else {
		return ""
	}
}
